export default {
  namespaced:true,
  
  state:() => ({
    cart:JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  mutations:{
    addToCart(state,goods){
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      console.log(findResult);
      if(!findResult){
        state.cart.push(goods)
      }else{
        findResult.goods_count ++
      }
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    updateGoodsState(state,goods){
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_state = goods.goods_state
        this.commit('m_cart/saveToStorage')
        
      }
    },
    
    updateGoodsCount(state,goods){
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
      
    },
    deleteGoods(state,id){
      const index = state.cart.indexOf(x => x.goods_id === id)
      if(index){
        state.cart.splice(index,1)
        this.commit('m_cart/saveToStorage')
      } 
    },
    updateAllState(state,newState){
      state.cart.forEach(x => x.goods_state = !newState)
    }
  },
  getters:{
    total(state){
      let c = 0
      state.cart.forEach(x => c += x.goods_count)
      return c
    },
    totalAmount(state){
      let b = 0
      state.cart.forEach((x) => {
        if(x.goods_state){
          b += (x.goods_price * x.goods_count)
        }
      } )
      return b
    },
    checkedAll(state){
      let c = true
      state.cart.forEach(x => c = c && x.goods_state)
      return c
    },
    totalCount(state){
      let a = 0
      state.cart.forEach((x) => {
        if(x.goods_state){
          a += x.goods_count
        }
      })
      return a
    }
  }

}